package cn.sdhuijin.service;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

import org.springframework.stereotype.Service;

import cn.sdhuijin.dao.DeductionDao;
import cn.sdhuijin.dao.StandardDao;
import cn.sdhuijin.dao.StandardItemDao;
import cn.sdhuijin.dao.TargetDao;
import cn.sdhuijin.model.Deduction;
import cn.sdhuijin.model.StandardItem;
import cn.sdhuijin.model.Target;
import cn.sdhuijin.utils.CommonUtil;

/**
 * @author sunp@sdhuijin.cn:
 * @version 创建时间：2015年5月11日 下午5:00:57 类说明
 */
@Service
public class DeductionServiceImpl implements DeductionService {

	@Inject
	private StandardDao standardDao;

	@Inject
	private StandardItemDao standardItemDao;

	@Inject
	private TargetDao targetDao;

	@Inject
	private DeductionDao deductionDao;

	@Inject
	private EntityManagerFactory entityManagerFactory;

	@Override
	public void BatchSave(List<LinkedHashMap<String, Object>> deductions) {
		for (int i = 0; i < deductions.size(); i++) {
			Deduction deduction = new Deduction();
			LinkedHashMap<String, Object> map = deductions.get(i);

			Long targetId = Long.valueOf(map.get("targetId").toString());
			Long standardItemId = Long.valueOf(map.get("standardItem")
					.toString());
			double score = Double.valueOf(map.get("score").toString());
			String description = map.get("description").toString();

			StandardItem standardItem = standardItemDao.findOne(standardItemId);
			Target target = targetDao.findOne(targetId);
			if (standardItem != null && target != null) {
				deduction.setStandardItem(standardItem);
				deduction.setTarget(target);
				deduction.setDate(new Date());
				deduction.setDescription(description);
				deduction.setScore(score);
				deductionDao.save(deduction);
			}
		}

	}

	@Override
	public Map<String, Object> countAllDetachmentSumScore() {
		EntityManager entityManager = null;
		Query query = null;
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			entityManager = entityManagerFactory.createEntityManager();
			query = entityManager
					.createNativeQuery("SELECT t.id AS id, t.`name` AS `name`, "
							+ "IFNULL(Sum(d.score),0) AS sumscore "
							+ "FROM target AS t "
							+ "LEFT JOIN deduction AS d ON t.id = d.target_id "
							+ "WHERE t.`level` = 1 AND t.isDeleted = 0 AND (d.isDeleted = 0 OR d.isDeleted IS NULL) "
							+ "GROUP BY t.id ORDER BY sumscore DESC");
			List list = query.getResultList();
			Long[] xId = new Long[list.size()];
			Double[] frontMonth = new Double[list.size()];
			Double[] currentMonth = new Double[list.size()];
			String[] xName = new String[list.size()];
			if (list != null) {
				for (int i = 0; i < list.size(); i++) {
					Object[] objs = (Object[]) list.get(i);
					xId[i] = Long.parseLong(objs[0].toString());
					frontMonth[i] = Double.parseDouble(objs[2].toString());
					currentMonth[i] = Double.parseDouble(objs[2].toString());
					xName[i] = objs[1].toString();
				}
			}
			map.put("xId", xId);
			map.put("frontMonth", frontMonth);
			map.put("currentMonth", currentMonth);
			map.put("xName", xName);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (entityManager != null) {
				entityManager.close();
			}
		}
		return map;
	}

	@Override
	public Map<String, Object> countStandardFolderPercent(Long id) {
		EntityManager entityManager = null;
		Query query = null;
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			entityManager = entityManagerFactory.createEntityManager();
			query = entityManager
					.createNativeQuery("SELECT Sum(d.score) AS sumscore, sf.`name` AS `name` FROM standardfolder AS sf LEFT JOIN standard AS s ON sf.standard_id = s.id LEFT JOIN target AS t ON t.standard_id = s.id LEFT JOIN standarditem AS si ON si.standardFolder_id = sf.id LEFT JOIN deduction AS d ON si.id = d.standardItem_id WHERE d.target_id = t.id AND t.id = ? GROUP BY sf.id ORDER BY sumscore DESC");
			query.setParameter(1, id);
			List list = query.getResultList();
			Double[] score = new Double[list.size()];
			Double[] percent = new Double[list.size()];
			String[] sName = new String[list.size()];
			Double sumScore = 0.0;
			if (list != null) {
				for (int i = 0; i < list.size(); i++) {
					Object[] objs = (Object[]) list.get(i);
					score[i] = Double.parseDouble(objs[0].toString());
					sumScore = sumScore + score[i];
					sName[i] = objs[1].toString();
				}
			}
			for (int j = 0; j < score.length; j++) {
				percent[j] = CommonUtil.getPercent(score[j], sumScore);
			}
			map.put("percent", percent);
			map.put("sName", sName);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (entityManager != null) {
				entityManager.close();
			}
		}
		return map;
	}
}
